package com.woniu.service.impl;

import com.woniu.entity.CustomerInfos;
import com.woniu.entity.UserInfos;
import com.woniu.mapper.UserInfosMapper;
import com.woniu.service.CustomerService;
import com.woniu.service.IUserInfosService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.util.ResultVO;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Random;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Gapper
 * @since 2021-03-29
 */
@Service
public class UserInfosServiceImpl extends ServiceImpl<UserInfosMapper, UserInfos> implements IUserInfosService {

    @Autowired
    UserInfosMapper mapper;

    @Autowired
    CustomerService customerService;

    @Override
    public boolean AddUserInfo(UserInfos user) {
        //随机生成字符串5位数字符串，组成盐
        String codes = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        Random random = new Random();
        StringBuilder randomStr = new StringBuilder();
        for (int i = 0; i < 5; i++) {
            randomStr.append(codes.charAt(random.nextInt(62)));
        }
        String salt=randomStr.toString();

        //对密码进行加密处理
        SimpleHash sh = new SimpleHash("MD5",user.getUserPwd(), salt, 1024);

        //将盐和加密后的密码存入user对象
        user.setSalt(salt);
        user.setUserPwd(sh.toHex());

        int i = mapper.insert(user);

        if (i>0){
            return true;
        }

        return false;
    }

    @Override
    public boolean DeleteUserInfo(Integer userId) {
        //先查询用户是否拥有客户，拥有客户的用户无法删除
        ResultVO resultVO = customerService.GetCustomerInfoByUserId(userId);
        List<CustomerInfos> customers = (List<CustomerInfos>) resultVO.getData();
        if (customers.size()!=0){
            return false;
        }

        int i = mapper.deleteById(userId);
        if (i>0){
            return true;
        }
        return false;
    }
}
